<?php

namespace App\Repository\Repositories;

use App\Http\Controllers\api\PaymentApiController;
use App\Http\Controllers\Controller;
use App\Models\Commission;
use App\Models\StoreHead;
use App\Models\StoreOrder;
use App\Models\User;
use App\Repository\RepositoryInterface\CommissionInterface;
use Dcat\EasyExcel\Excel;

class CommissionRepositories extends Controller implements CommissionInterface
{
    protected $commission;

    public function __construct(Commission $commission){
        $this->commission = $commission;
    }
    /**
     * @return \Illuminate\Http\JsonResponse
     * 佣金列表查询
     * zyy
     */
    public function comWithHeadWithOrder(){
        try {
            $commissionListData = $this->commission->with(["comWithHead","comWithOrder"])->OrderBy("cutofftime","desc")->paginate(5);
            return parent::success("列表查询成功",$commissionListData);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }
    /**
     * @param $searchInfo
     * @return mixed
     * 团长佣金搜索
     * 佣金状态
     * 结算时间
     * 团长主键
     * 团长查询
     */
    public function comSearch($searchInfo){
        try {
            $searchData = $this->commission->with(["comWithHead","comWithOrder"])->when($searchInfo,function ($query,$searchInfo){
                if($searchInfo['status'] != ""){
                    $query->where("status",$searchInfo['status']);
                }
            })->when($searchInfo,function ($query,$searchInfo){
                if($searchInfo['cutofftime'] != ""){
                    $query->where("cutofftime",$searchInfo['cutofftime']);
                }
            })->when($searchInfo,function ($query,$searchInfo){
                if($searchInfo['headName'] != ""){
                    $headId = StoreHead::getHeadId($searchInfo['headName']);
                    foreach ($headId as $val){
                        $query->where("hid",$val['id']);
                    }
                }
            })->paginate(5)->toArray();
            return parent::success("搜索查询成功",$searchData);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse|string
     * 团长佣金流水计算
     * 该团长的会员等级
     * 每个订单的实际支付金额
     * 循环取流水 进行修改
     */
    public function comOrderStatusPrice(){
        try {
            $comOrderStatus = $this->commission->where("orderStatus","1")->get(["sid","isVip"])->toArray();
            $sidAll = [];
            foreach ($comOrderStatus as $key => $val){
                $sidAll[$key] = $val['sid'];
            }
            $totalPrice = [];
            foreach ($sidAll as $k=>$v){
                $totalPrice[$k] = StoreOrder::orderStatusPrice($v);
            }
            $incomeission = [];
            $oddsAll = [];
            foreach ($totalPrice as $k=>$v){
                foreach ($comOrderStatus as $key=>$val){
                    switch ($val['isVip']){
                        case 0:
                            $oddsAll[$key] = 0.001;
                            break;
                        case 1:
                            $oddsAll[$key] = 0.005;
                            break;
                        case 2:
                            $oddsAll[$key] = 0.010;
                            break;
                        case 3:
                            $oddsAll[$key] = 0.015;
                            break;
                        default:break;
                    }
                    foreach ($v as $vv){
                        $incomeission[$k] = $vv['total_price']*$oddsAll[$key];
                    }
                }
            }
            for ($i=0;$i<count($sidAll);$i++){
                $this->commission->updataCommission($sidAll[$i],$incomeission[$i]);
            }
            return parent::success("流水计算完成");
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * 导出团长流水佣金Excel
     */
    public function commissionExcel(){
        $commissionData = $this->commission->with(["comWithHead","comWithOrder"])->OrderBy("cutofftime","desc")->get()->toArray();
        try {
            $commissionExcelData = [];
            foreach ($commissionData as $val) {
                $commissionExcelData[] = [
                    "id" => $val['id'],
                    "name" => $val['com_with_head']['name'],
                    "phone" => $val['com_with_head']['phone'],
                    "incomeission" => $val['incomeission'],
                    "cutofftime" => $val['cutofftime']
                ];
            }
            $headings = ['id'=>'ID','name'=>'团长','phone'=>'手机','incomeission'=>"所得佣金","cutofftime"=>"结束时间"];
            Excel::export($commissionExcelData)->headings($headings)->download('commission.xlsx');
            return parent::success("导出excel成功",);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }
    /**
     * api
     * @return \Illuminate\Http\JsonResponse
     * 显示总金额
     */
    public function comGroupPrice($uid){
        try {
            $GroupBossPrice = User::groupDataPrice($uid)->toArray();
            return parent::success("团长佣金",$GroupBossPrice);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * api
     * @param $groupDataPrice
     * @return \Illuminate\Http\JsonResponse|void
     * 查询该团长的佣金
     * 提现佣金
     * uid             用户id
     * bank_code       银行卡(根据提现方式而定  alipay or wechat or bank_code)
     * extract_price   提现金额
     * extract_type    提现方式
     */
    public function priceTure($groupDataPrice){
        try {
            $groupBoss = User::groupDataPrice($groupDataPrice['uid']);
            $groupBossAgePrice = $groupBoss->brokerage_price;
            if($groupBossAgePrice < 100){
                return parent::error("最小提现金额为100元！");
            }
            if($groupBossAgePrice < $groupDataPrice['extract_price']){
                return parent::error("没有那么多佣金！");
            }

            $priceGroupTrue = (new PaymentApiController)->extract($groupDataPrice);
            if($priceGroupTrue){
                $priceWorkLast =$groupBossAgePrice - $groupDataPrice['extract_price'];
                $data = [
                    "uid"=>$groupDataPrice['uid'],
                    "brokerage_price"=>$priceWorkLast
                ];
                User::upGroupBossPrice($data);
                return parent::success("佣金提现成功！");
            }
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }
}
